package com.zhuangjie.rider.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuangjie.base.enums.MoneyRecordStatus;
import com.zhuangjie.order.pojo.RiderDeliveryFeeForRiderOrderAccounting;
import com.zhuangjie.rider.constant.RiderDeliveryIncomeEarliestArrivalTimeConstant;
import com.zhuangjie.rider.entity.RiderMoneyRecord;
import com.zhuangjie.rider.entity.RiderOrderAccountingRecord;
import com.zhuangjie.rider.mapper.RiderOrderAccountingRecordMapper;
import com.zhuangjie.rider.service.DeliveryOrderService;
import com.zhuangjie.rider.service.RiderMoneyRecordService;
import com.zhuangjie.rider.service.RiderOrderAccountingRecordService;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.transaction.Propagation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 骑手配送订单入账记录表 服务实现类
 * </p>
 *
 * @author zhuangjie
 * @since 2024-04-02
 */
@Service
public class RiderOrderAccountingRecordServiceImpl extends ServiceImpl<RiderOrderAccountingRecordMapper, RiderOrderAccountingRecord> implements RiderOrderAccountingRecordService {

    @Autowired
    private RiderMoneyRecordService riderMoneyRecordService;

    @Autowired
    private DeliveryOrderService deliveryOrderService;

    @Override
    @GlobalTransactional(propagation = Propagation.REQUIRED)
    public void createOrderAccounting(Long orderId) {
        // 获取订单是否已经完成，并且返回订单店铺的纯利润用来准备入账
        RiderDeliveryFeeForRiderOrderAccounting shopProfitForShopOrderAccountingVO = deliveryOrderService.queryRiderDeliveryFeeForRiderOrderAccounting(orderId);
        // 插入shop_money_record
        RiderMoneyRecord riderMoneyRecord = new RiderMoneyRecord();
        riderMoneyRecord.setRiderId(shopProfitForShopOrderAccountingVO.getRiderId());
        riderMoneyRecord.setOperationAmount(shopProfitForShopOrderAccountingVO.getOrderDeliveryFee());
        riderMoneyRecord.setStatus(MoneyRecordStatus.WAITING_FOR_ENTRY.getCode());
        riderMoneyRecord.setSourceDescribe("骑手配送费入账");
        riderMoneyRecord.setEarliestArrivalTime(RiderDeliveryIncomeEarliestArrivalTimeConstant.get());
        riderMoneyRecordService.save(riderMoneyRecord);

        // 插入shop_order_accounting_record记录
        RiderOrderAccountingRecord riderOrderAccountingRecord = new RiderOrderAccountingRecord();
        riderOrderAccountingRecord.setOrderId(orderId);
        riderOrderAccountingRecord.setMoneyRecordId(riderMoneyRecord.getId());
        this.save(riderOrderAccountingRecord);

    }
}
